<template>
  <div :id="id" ref="table" v-show="false">
    <a-layout class="admin-layout-main mycustom">
      <a-icon @click="toggleScreen" class="action" :type="fullScreen ? 'fullscreen-exit' : 'fullscreen'" />
      <span class="time">{{ dateTime }}</span>
      <a-row>
        <div class="titleDiv" :style="{ backgroundImage: 'url(' + require('@/assets/img/title.png') + ')' }">
          <img class="title_l" src="@/assets/img/title_l.png">
          电子仓可视化看板
          <img class="title_r" src="@/assets/img/title_r.png">
        </div>
      </a-row>
      <a-row style="margin-top: 10px">
        <a-col style="padding: 0 12px" :xl="7" :md="24" :sm="24">
          <a-card :style="{ backgroundImage: 'url(' + require('@/assets/img/card.png') + ')' }">
            <a-col :sm="12" :md="12" :xl="12">
              <div class="head-info">
                <div>当班入库</div>
                <p>{{ inCount }}</p>
              </div>
            </a-col>
            <a-col :sm="12" :md="12" :xl="12">
              <div class="head-info">
                <div>当班出库</div>
                <p>{{ outCount }}</p>
              </div>
            </a-col>
            <a-col :sm="24" :md="24" :xl="24">
              <div class="chartTitle">实时入库</div>
              <div id="inContainer" style="height:180px;"></div>
            </a-col>
          </a-card>
          <a-card :style="{ backgroundImage: 'url(' + require('@/assets/img/card.png') + ')' }"
            style="margin-top:15px;">
            <a-col :sm="24" :md="24" :xl="24">
              <div class="chartTitle" style="padding:20px">实时出库</div>
              <div id="outContainer" style="height:229px;"></div>
            </a-col>
          </a-card>
        </a-col>

        <a-col :xl="10" :md="24" :sm="24">
          <a-card :style="{ backgroundImage: 'url(' + require('@/assets/img/card.png') + ')' }">
            <div class="card-title" :style="{ backgroundImage: 'url(' + require('@/assets/img/c_title.png') + ')' }">
              <div>设备运行状况</div>
            </div>
            
          </a-card>
        </a-col>

        <a-col style="padding: 0 12px" :xl="7" :md="24" :sm="24">
          <a-card :style="{ backgroundImage: 'url(' + require('@/assets/img/card.png') + ')' }">
            <div class="card-title" :style="{ backgroundImage: 'url(' + require('@/assets/img/c_title.png') + ')' }">
              <div>储位使用率</div>
            </div>
            <div style="display:flex">
              <div id="pieContainer" style="height:200px;margin: 40px 0 9px 0;width: calc(100% - 100px);"></div>
              <div style="width:100px;margin-top: 50px;">
                <div class="head-info" style="margin:10px 0">
                  <div style="font-size:15px">总储位</div>
                  <p style="font-size:15px">5152</p>
                </div>
                <div class="head-info" style="margin:10px 0">
                  <div style="font-size:15px">已使用</div>
                  <p style="font-size:15px">{{ count }}</p>
                </div>
                <div class="head-info" style="margin:10px 0">
                  <div style="font-size:15px">剩余</div>
                  <p style="font-size:15px">{{ 5152 - count }}</p>
                </div>
              </div>
            </div>
          </a-card>
          <a-card :style="{ backgroundImage: 'url(' + require('@/assets/img/card.png') + ')' }"
            style="margin-top:15px;">
            <div class="card-title" :style="{ backgroundImage: 'url(' + require('@/assets/img/c_title.png') + ')' }">
              <div>库存缺料预警</div>
            </div>

            <div style="display:flex">
              <div id="plotsContainer" style="height:200px;margin: 40px 0 9px 0;width: calc(100% - 300px);"></div>
              <a-table style="width:300px;margin-top: 15px;" :columns="warnColumns" :dataSource="warnData"
                :pagination="false" :rowKey="(warnData) => warnData.PartNo" class="warnScrollTable"
                :scroll="{ y: 180 }">
              </a-table>
            </div>
          </a-card>
        </a-col>
      </a-row>
      <a-row style="margin: 10px 12px">
        <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card class="top0" :style="{ backgroundImage: 'url(' + require('@/assets/img/card_big.png') + ')' }"
            style="height:289px">
            <div class="card-title" :style="{ backgroundImage: 'url(' + require('@/assets/img/c_title.png') + ')' }">
              <div>SMT实时物料需求播报</div>
              <img class="title_l" src="@/assets/img/title_l.png">
              <img class="title_r" src="@/assets/img/title_r.png">
            </div>
            <a-table :columns="taskColumns" :dataSource="taskData" :pagination="false"
              :rowKey="(taskData) => taskData.Id" class="scrollTable" :scroll="{ y: 180 }">
              <template slot="time" slot-scope="text">
                {{ text | dateTimeFormat }}
              </template>
              <template slot="timeLong" slot-scope="text, record">
                {{ record.CreateDt | dateTimeLong }}
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </a-layout>
  </div>
</template>

<script>
import { Liquid, measureTextWidth, Column, Pie } from '@antv/g2plot'
// import { boardService } from '/src/services'
import moment from 'moment'


var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]

export default {
  name: 'Home',
  data() {
    return {
      loading: true,
      inCount: 0,
      outCount: 0,
      count: 0,
      useRate: 0,
      grainRate: 0,
      runTime: '',
      freeTime: '',
      liquidPlot: [],
      piePlot: [],
      inPlot: [],
      outPlot: [],
      isYellow: false,
      isGreen: false,
      isRed: false,
      exLocation: 1,
      exRack: 1,
      exIPC: 1,
      timer: null,
      scrolltimer: null,
      numtimer: null,
      intimer: null,
      outtimer: null,
      tasktimer: null,
      inData: [],
      outData: [],
      warnData: [],
      warnColumns: [
        {
          title: '料号',
          dataIndex: 'PartNo',
          width: 100,
          align: 'center'
        },
        {
          title: '下线盘数',
          dataIndex: 'MinNum',
          width: 100,
          align: 'center',
          class: 'blue'
        },
        {
          title: '库存盘数',
          dataIndex: 'Num',
          width: 70,
          align: 'center',
          class: 'orange'
        },
      ],
      taskData: [],
      taskColumns: [
        {
          title: 'NO',
          customRender: (text, record, index) => `${index + 1}`,
          width: 50,
          align: 'center'
        },
        {
          title: '任务号',
          dataIndex: 'TASKNO',
          width: 150,
          align: 'center'
        },
        {
          title: 'PKGID',
          dataIndex: 'PKGID',
          width: 180,
          align: 'center'
        },
        {
          title: '料号',
          dataIndex: 'PARTNO',
          width: 120,
          align: 'center'
        },
        {
          title: '储位',
          dataIndex: 'LOCATION',
          width: 100,
          align: 'center'
        },
        {
          title: '线体',
          dataIndex: 'LINENAME',
          width: 100,
          align: 'center'
        },
        {
          title: '轨道号',
          dataIndex: 'TRACKNO',
          width: 150,
          align: 'center'
        },
        {
          title: '叫料时间',
          dataIndex: 'CreateDt',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'time' }
        },
        {
          title: '已叫料时长',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'timeLong' }
        },
        {
          title: '出库完成时间',
          dataIndex: 'FinishDt',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'time' }
        },
        {
          title: '发料状况',
          dataIndex: 'Status',
          width: 100,
          align: 'center'
        },
      ],
      dateTime: moment().format('YYYY-MM-DD HH:mm:ss ') + weeks[moment().days()],
      fullScreen: false,
      id: `${new Date().getTime()}-${Math.floor(Math.random() * 10)}`,
      isLoading: false,
    }
  },
  filters: {
    dateTimeFormat(val) {
      if (val == null) return ''
      return val.replace('T', ' ').substring(0, 19)
    },
    dateTimeLong(val) {
      if (val == null) return ''
      var time = val.replace('T', ' ')
      return (moment().diff(moment(time), 's') / 60).toFixed(2);
    }
  },
  mounted: function () {
    // this.initChart()
    // this.loadData()

    // this.tasktimer = setInterval(() => {
    //   this.loadData();
    // }, 1000 * 5)
    this.timer = setInterval(() => {
      this.dateTime = moment().format('YYYY-MM-DD HH:mm:ss ') + weeks[moment().days()]
    }, 1000)
    // this.scrolltimer = setInterval(() => {
    //   this.scrollData()
    //   this.warnScrollData()
    // }, 100)
  },
  destroyed() {
    clearInterval(this.timer)
    clearInterval(this.scrolltimer)
    clearInterval(this.numtimer)
    clearInterval(this.intimer)
    clearInterval(this.outtimer)
    clearInterval(this.tasktimer)
  },
  beforeDestroy() {
    this.removeListener()
  },
  created() {
    this.addListener()
  },
  methods: {
    async loadData() {
      // var result = await boardService.getBoardData()
      // if (result && result.data) {
      //   this.taskData = result.data.taskData
      //   this.inData = result.data.inData
      //   this.outData = result.data.outData
      //   this.warnData = result.data.warnData


      //   var data = result.data.num
      //   this.inCount = data.InCount
      //   this.outCount = data.OutCount
      //   this.count = data.Count
      //   this.isRed = data.RedLight === '亮'
      //   this.isYellow = data.YellowLight === '亮'
      //   this.isGreen = data.GreenLight === '亮'

      //   this.grainRate = data.GrainRate
      //   this.runTime = data.RunTime
      //   this.freeTime = data.FreeTime
      //   this.useRate = 1 - this.warnData.length / data.LimitCount

      //   this.inPlot.changeData(this.inData)
      //   this.outPlot.changeData(this.outData)
      //   this.changePie()
      //   this.liquidPlot.changeData(this.useRate > 1 ? 1 : this.useRate)
      // }
    },
    changePie() {
      const pieData = [
        { type: '已使用', value: this.count },
        { type: '剩余', value: 5152 - this.count },
      ];
      this.piePlot.changeData(pieData)
    },
    initChart() {
      const data = [
        {
          Time: '8-10',
          Count: 0,
        },
        {
          Time: '10-12',
          Count: 0,
        },
        {
          Time: '12-14',
          Count: 0,
        },
        {
          Time: '14-16',
          Count: 0
        },
        {
          Time: '16-18',
          Count: 0,
        },
        {
          Time: '18-20',
          Count: 0,
        }
      ];
      const option = {
        data,
        appendPadding: [10],
        xField: 'Time',
        yField: 'Count',
        seriesField: 'Time',
        color: ['#FFC000', '#43D7E3', '#3575F1', '#5B9BD5', '#5B9BD5', '#7030A0'],
        legend: false,
        label: {
          position: top,
          dy: '-20px',
          // 配置样式
          style: {
            fill: '#FFFFFF',
            fontSize: 15
          },
        },
        xAxis: {
          label: {
            style: {
              fill: '#FFFFFF',
              fontSize: 15
            },
          }
        },
        yAxis: {
          grid: {
            line: null,
          },
          label: {
            style: {
              fill: '#FFFFFF',
              fontSize: 15
            },
          }
        },
      }
      const inPlot = new Column('inContainer', option);
      inPlot.render();
      this.inPlot = inPlot;

      const outPlot = new Column('outContainer', option);
      outPlot.render();
      this.outPlot = outPlot;

      const pieData = [
        { type: '已使用', value: 0 },
        { type: '剩余', value: 5152 },
      ];
      const piePlot = new Pie('pieContainer', {
        data: pieData,
        angleField: 'value',
        colorField: 'type',
        pieStyle: { lineWidth: 0 },
        color: ({ type }) => {
          if (type === '已使用') {
            return 'l(0) 0:#E6008C 0.38:#A215C3 1:#5D29FA';
          }
          return '#767171';
        },
        innerRadius: 0.6,
        label: false,
        legend: false,
        statistic: {
          title: false,
          content: {
            style: {
              whiteSpace: 'pre-wrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              color: '#fff',
              fontSize: 16
            },
            customHtml: (container, view, datum, data) => {
              var value = 0;
              for (let index = 0; index < data.length; index++) {
                const element = data[index];
                if (element.type === '已使用') {
                  value = '<div><span style="font-size:30px;line-height:60px;font-style:italic">' + (element.value * 100 / 5152).toFixed(0) + '%\r</span>使用率</div>';
                }
              }
              return value + ``
            },

            //content: '0%\n使用率',
          },
        },
      });
      piePlot.render();
      this.piePlot = piePlot;

      const liquidPlot = new Liquid('plotsContainer', {
        percent: this.useRate,
        statistic: {
          title: {
            formatter: () => '库存水位',
            style: ({ percent }) => ({
              fill: percent > 0.6 ? 'white' : 'white'
            })
          },
          content: {
            style: ({ percent }) => ({
              fontSize: 60,
              lineHeight: 1,
              fill: percent > 0.6 ? 'white' : 'white'
            }),
            customHtml: (container, view, { percent }) => {
              const { width, height } = container.getBoundingClientRect()
              const d = Math.sqrt(
                Math.pow(width / 2, 2) + Math.pow(height / 2, 2)
              )
              const text = `${(percent * 100).toFixed(0)}%`
              const textWidth = measureTextWidth(text, { fontSize: 60 })
              const scale = Math.min(d / textWidth, 1)
              return `<div style="width:${d}px;display:flex;align-items:center;justify-content:center;font-size:${scale}em;line-height:${scale <= 1 ? 1 : 'inherit'
                }">${text}</div>`
            }
          }
        },
        liquidStyle: ({ percent }) => {
          return {
            fill: percent > 0.45 ? '#5B8FF9' : '#FAAD14',
            stroke: percent > 0.45 ? '#5B8FF9' : '#FAAD14'
          }
        },
        color: () => '#5B8FF9'
      })
      liquidPlot.render()
      this.liquidPlot = liquidPlot
    },
    scrollData() {
      var scrollTable = document.getElementsByClassName('scrollTable')[0]
      var scrollBody = scrollTable.getElementsByClassName('ant-table-body')[0];
      if (scrollBody) {
        if ((scrollBody.scrollHeight - scrollBody.clientHeight) <= scrollBody.scrollTop + 1) {
          scrollBody.scrollTop = 0;
        } else {
          scrollBody.scrollTop += 1;
        }
      }
    },
    warnScrollData() {
      var scrollTable = document.getElementsByClassName('warnScrollTable')[0]
      var scrollBody = scrollTable.getElementsByClassName('ant-table-body')[0];
      if (scrollBody) {
        if ((scrollBody.scrollHeight - scrollBody.clientHeight) <= scrollBody.scrollTop + 1) {
          scrollBody.scrollTop = 0;
        } else {
          scrollBody.scrollTop += 1;
        }
      }
    },
    toggleScreen() {
      if (this.fullScreen) {
        this.outFullScreen()
      } else {
        this.inFullScreen()
      }
    },
    inFullScreen() {
      const el = this.$refs.table
      el.classList.add('beauty-scroll')
      if (el.requestFullscreen) {
        el.requestFullscreen()
        return true
      } else if (el.webkitRequestFullScreen) {
        el.webkitRequestFullScreen()
        return true
      } else if (el.mozRequestFullScreen) {
        el.mozRequestFullScreen()
        return true
      } else if (el.msRequestFullscreen) {
        el.msRequestFullscreen()
        return true
      }
      this.$message.warn('对不起，您的浏览器不支持全屏模式')
      el.classList.remove('beauty-scroll')
      return false
    },
    outFullScreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      }
      this.$refs.table.classList.remove('beauty-scroll')
    },
    addListener() {
      document.addEventListener('fullscreenchange', this.fullScreenListener)
      document.addEventListener('webkitfullscreenchange', this.fullScreenListener)
      document.addEventListener('mozfullscreenchange', this.fullScreenListener)
      document.addEventListener('msfullscreenchange', this.fullScreenListener)
    },
    removeListener() {
      document.removeEventListener('fullscreenchange', this.fullScreenListener)
      document.removeEventListener('webkitfullscreenchange', this.fullScreenListener)
      document.removeEventListener('mozfullscreenchange', this.fullScreenListener)
      document.removeEventListener('msfullscreenchange', this.fullScreenListener)
    },
    fullScreenListener(e) {
      if (e.target.id === this.id) {
        this.fullScreen = !this.fullScreen
      }
    }
  }
}
</script>
<style lang="less">
@import 'index';
</style>
